import localStore from 'store'
import { CACHE_EXPIRE } from '@/config'

const store: any = localStore.enabled ? localStore : {}

const plus = (key: string) => `POIZON-${key}`

/**
 * @获取
 * @param {*} key 键名
 */
const get = (key: string) => {
  const name = plus(key)
  const raw = store.get ? store.get(name) : store[name]
  if (!raw) return null

  const itvl = Date.now() - raw.timeStamp
  if (raw.ttl > itvl) return raw.value

  remove(name) // 缓存过期，清除缓存
  return null
}

/**
 * @设置
 * @param {*} key 键名
 * @param {*} value 值
 * @param {*} ttl (可选) 有效时间长度 单位毫秒
 */
const set = (key: string, value: any, ttl = CACHE_EXPIRE) => {
  const name = plus(key)
  const raw = {
    key: name,
    timeStamp: Date.now(),
    ttl: ttl || false,
    value,
  }

  store.set ? store.set(name, raw) : (store[name] = raw)
}

/**
 * @删除
 * @param {*} key 键名
 */
const remove = (key: string) => {
  const name = plus(key)
  if (!name || typeof name !== 'string') return
  store.remove ? store.remove(name) : delete store[name]
}

export default {
  get,
  set,
  remove,
}
